const querystring = require('querystring')
const handleBlogRouter = require('./src/router/blog')
const handleUserRouter = require('./src/router/user')
const { get, set } = require('./src/db/redis')

const getPostData = req => {
  let promise = new Promise((resolve, reject) => {
    if (req.method == 'GET') {
      resolve({})
      return
    }
    if (req.headers['content-type'] !== 'application/json') {
      resolve({})
      return
    }
    let postData = ''
    req.on('data', chunk => {
      postData += chunk.toString()
    })
    req.on('end', () => {
      if (!postData) {
        resolve({})
        return
      }
      resolve(JSON.parse(postData))
    })
  })
  return promise
}

const getOneDay = () => {
  let date = new Date(Date.now() + 24 * 60 * 60)
  return date.toUTCString()
}

const sessionData = {}

const serverHandle = async (req, res) => {
  res.setHeader('Content-type', 'application/json')

  const url = req.url
  req.path = url.split('?')[0]

  // 解析cookie
  req.cookie = {}
  const cookieStr = req.headers.cookie || ''
  cookieStr.split(';').forEach(item => {
    if (!item) {
      return
    }
    const arr = item.split('=')
    const key = arr[0].trim()
    const value = arr[1].trim()
    req.cookie[key] = value
  })

  // 处理sessionData
  // let needSetCookie = false
  // let userId = req.cookie.userId
  // if (!userId) {
  //   userId = Date.now() + '_' + Math.random()
  //   needSetCookie = true
  // }

  // if (!sessionData[userId]) {
  //   sessionData[userId] = {}
  // }
  // req.session = sessionData[userId]

  // 处理redis
  let needSetCookie = false
  let userId = req.cookie.userId
  if (!userId) {
    userId = Date.now() + '_' + Math.random()
    needSetCookie = true
    set(userId, {})
  }
  req.sessionId = userId
  let result = await get(req.sessionId)
  if (result == null) {
    set(req.sessionId, {})
    // 设置session
    req.session = {}
  } else {
    req.session = result
  }
  
  console.log(req.session)
  // 处理query
  req.query = querystring.parse(url.split('?')[1])

  req.body = await getPostData(req)
  // 处理路由
  const blogData = await handleBlogRouter(req, res)
  if (blogData) {
    if (needSetCookie) {
      res.setHeader(
        'Set-Cookie',
        `userId=${userId} ; path=/; httpOnly; expires=${getOneDay()}`
      )
    }
    res.end(JSON.stringify(blogData))
    return
  }
  const userData = await handleUserRouter(req, res)
  if (userData) {
    if (needSetCookie) {
      res.setHeader(
        'Set-Cookie',
        `userId=${userId} ; path=/; httpOnly; expires=${getOneDay()}`
      )
    }
    res.end(JSON.stringify(userData))
    return
  }

  // 404处理
  res.writeHead('404', { 'Content-type': 'text/plain' })
  res.write('404 Not Found!\n')
  res.end()
}

module.exports = serverHandle
